<template>
  <div>
    <!-- 筛选搜索 -->
    <SearchForm
      :currentPlaceholder="currentPlaceholder"
      :currentLabel="currentLabel"
      @submit-search="submitSearch"
      @rest-search="restSearch"
    >
      <template #inputSelect>
        <div>
          <el-form-item label="推荐状态：" prop="selectStatus">
            <el-select v-model="value" class="m-2" placeholder="全部">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </div>
      </template>
    </SearchForm>
    <!-- 选择品牌 -->
    <addData>
      <template #btnText>
        <el-button type="primary">选择品牌</el-button>
      </template>
    </addData>
    <!-- 数据列表 -->
    <el-table
      :border="true"
      ref="multipleTableRef"
      :data="tableData"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column align="center" type="selection" width="60" />
      <el-table-column align="center" label="编号" property="id" width="120">
      </el-table-column>
      <el-table-column
        align="center"
        property="brandName"
        label="品牌名称"
        width="500"
      />
      <el-table-column
        align="center"
        property="address"
        label="是否推荐"
        width="200"
      >
        <template #default="scope">
          <el-switch
            v-model="scope.row.recommendStatus"
            :active-value="1"
            :inactive-value="0"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column align="center" property="sort" label="排序" />
      <el-table-column align="center" label="状态">
        <template #default="scope">
          <div>{{ scope.row.recommendStatus === 1 ? "推荐中" : "未推荐" }}</div>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        property="address"
        label="操作"
        width="180"
      >
        <template #default="scope">
          <span class="role">设置排序</span>
          <span class="edit">删除</span>
        </template>
      </el-table-column>
    </el-table>
    <!-- 批量操作数据 -->
    <OperateList @submit-operation="submitOperation"></OperateList>
    <!-- 分页插件 -->
    <Pagination
      :total="total"
      :pageSize="pageSize"
      :currentPageNum="currentPageNum"
      :currentPageSize="currentPageSize"
      @changePageSize="changePageSize"
      @changePageNum="changePageNum"
    ></Pagination>
  </div>
</template>

<script lang="ts" setup>
import { reactive, toRefs, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { ElTable } from "element-plus";
// 网络请求接口
import {
  getBrandListApi,
  changeRecommendStatusApi,
  deleteRecommendApi,
} from "../../request/api";
// 组件
import SearchForm from "../../components/SearchForm.vue";
import addData from "../../components/addData.vue";
import Pagination from "../../components/Pagination.vue";
import OperateList from "../../components/OperateList.vue";

// 列表数据接口类型
interface brandListItf {
  brandId: number;
  brandName: string;
  id: number;
  recommendStatus: number;
  sort: number;
}

const value = ref(""); // 推荐选框的默认值
// 下拉框选项
const options = [
  {
    value: "未推荐", // 需要传递到后端的标识符
    label: "未推荐",
  },
  {
    value: "推荐中", // 需要传递到后端的标识符
    label: "推荐中",
  },
];
// 全选反选
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
// 选中的数据
const multipleSelection = ref<brandListItf[]>([]);

// 定义响应式数据
const state = reactive<{
  tableData: brandListItf[];
  pageSize: number[];
  total: number;
  currentPageNum: number;
  currentPageSize: number;
}>({
  tableData: [], // 列表数据
  pageSize: [5, 10, 15], // 分页插件选择一页显示n条数据的数组
  total: 0, // 列表数据总条数
  currentPageNum: 1, // 当前显示的是第几页
  currentPageSize: 5, // 当前一页显示n条数据
});
let { tableData, pageSize, total, currentPageNum, currentPageSize } =
  toRefs(state);
let currentPlaceholder = ref("品牌名称");
let currentLabel = ref("品牌名称：");

/*
 * 定义方法
 *
 */
// 封装请求列表数据方法
const getBrandList = (pageNum: number = 1, pageSize: number = 5) => {
  return new Promise((resolve, reject) => {
    getBrandListApi(pageNum, pageSize).then(res => {
      if (res.code === 200) {
        console.log(res);
        tableData.value = res.data.list;
        total.value = res.data.total;
        currentPageNum.value = res.data.pageNum;
        resolve(res);
      }
    });
  });
};

// 批量操作数据
const submitOperation = (recommendStatus: string) => {
  // 判断是否有选中数据
  if (multipleSelection.value.length !== 0 && recommendStatus) {
    if (recommendStatus === "2") {
      // 删除操作
      ElMessageBox.confirm("是否要删除数据?", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        // 将选中的数据更改为字符串格式(便于传递参数)
        let arr: string[] = [];
        multipleSelection.value.forEach(item => {
          arr.push(item.id + "");
        });
        let ids: string = arr.join(",");
        // 发送请求删除数据
        deleteRecommendApi({
          ids,
        }).then(res => {
          if (res.code === 200) {
            // 更新页面
            getBrandList().then(() => {
              ElMessage({
                type: "success",
                message: res.message,
              });
            });
          }
        });
      });
    } else {
      // 修改数据推荐状态
      ElMessageBox.confirm("是否要修改推荐状态?", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 将选中的数据更改为字符串格式(便于传递参数)
          let arr: string[] = [];
          multipleSelection.value.forEach(item => {
            arr.push(item.id + "");
          });
          let ids: string = arr.join(",");
          // 发送请求修改状态
          changeRecommendStatusApi({
            ids,
            recommendStatus,
          }).then(res => {
            if (res.code === 200) {
              // 更新数据
              getBrandList().then(() => {
                ElMessage({
                  type: "success",
                  message: res.message,
                });
              });
            }
          });
        })
        .catch(() => {});
    }
  } else {
    // 没有选中数据或者没有选择要修改的状态
    ElMessage({
      type: "warning",
      message:
        multipleSelection.value.length === 0
          ? "请至少选择一条数据"
          : "请选择批量操作类型",
    });
  }
};

// 改变页码
const changePageNum = (pageNum: number) => {
  currentPageNum.value = pageNum;
  getBrandList(currentPageNum.value, currentPageSize.value);
};

// 改变一页显示n条
const changePageSize = (pageSize: number) => {
  currentPageSize.value = pageSize;
  getBrandList(currentPageNum.value, currentPageSize.value);
};

// 全选反选
const toggleSelection = (rows?: brandListItf[]) => {
  if (rows) {
    rows.forEach(row => {
      // TODO: improvement typing when refactor table
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-expect-error
      multipleTableRef.value!.toggleRowSelection(row, undefined);
    });
  } else {
    multipleTableRef.value!.clearSelection();
  }
};

// 单选功能
const handleSelectionChange = (val: brandListItf[]) => {
  multipleSelection.value = val;
};

// 查询搜索功能
const submitSearch = (val: string) => {
  console.log(val); // 子组件数据
  console.log(value.value); // 本组件数据
};

// 重置清空功能
const restSearch = (formEl: { resetFields: () => {} }) => {
  formEl.resetFields(); // 子组件清空
  value.value = ""; // 本组件清空
};

// 页面加载请求数据
getBrandList();
</script>
<style lang="less" scoped>
:deep(.cell) {
  font-size: 10px !important;
}
.role,
.edit {
  cursor: pointer;
  color: #66b1ff;
}
.role {
  margin-right: 10px;
}
</style>
